# coding: utf-8
from pretreatment.Command_Check import Command_Check
from pretreatment.DTB_switching import DTB_Switching
from common.Scheduled_Tasks import Scheduled_Tasks
from pretreatment.Script_Settings import Script_Settings

import os


class Execute_Program():
    def __init__(self):
        self.sn=input("Please scan the SN QR code:")
        self.sn_number = self.sn[0:10].upper()

        self.work_dir_path = os.path.dirname(os.path.abspath(__file__))
        self.file_name=os.path.abspath(__file__)
        self.Xpath=os.popen("find / -name .Xauthority |head -1").read().strip()

        self.stask=Scheduled_Tasks()
        self.check = Command_Check(f'{self.work_dir_path}/config.ini')
        self.dtb=DTB_Switching(f'{self.work_dir_path}/config.ini',self.sn_number)
        self.sset=Script_Settings(f'{self.work_dir_path}/config.ini',self.sn_number)

    def main(self):
        lxterm_path = os.popen("sudo which lxterminal").read().strip()
        pyhton3_path = os.popen("sudo which python3").read().strip()
        chance_path=self.work_dir_path+'/Flag_detection.py'
        self.sset.main()
        if self.check.check() == 0 :
            task_commands=f"sleep 20;su root -c 'DISPLAY=:0.0 {lxterm_path} -e {pyhton3_path} {self.file_name}'"
            cat_commands= f"sleep 20;su root -c 'DISPLAY=:0.0 {lxterm_path} -e {pyhton3_path} {chance_path}'"
            cp_commands=f"sleep 10;cp {self.Xpath} /root/"
            if self.dtb.main() == 0 :
                #删除原有定时任务
                self.stask.delet_task()
                #添加新脚本定时任务
                self.stask.Set_restart_task(cp_commands,"copy Xauthority")
                if self.stask.check_function(cat_commands) == 1:
                    os.system("sudo reboot")
                else:
                    self.stask.Set_restart_task(cat_commands,'Task restart')
                    os.system("sudo reboot")
            else:
                if self.stask.check_function(task_commands) == 1:
                    os.system("sudo reboot")
                else:
                    self.stask.Set_restart_task(task_commands,'Check restart')
                    os.system("sudo reboot")
        else:
            print("done")



if __name__ == '__main__':
    cp_shell = os.popen("sudo find / -name .Xauthority|head -1").read().strip()
    os.system(f"sudo cp {cp_shell} /root/")
    ep = Execute_Program()
    # print(ep.work_dir_path)
    ep.main()